package com.yuanxiao.common.core.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.yuanxiao.common.core.result.R;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;

/**
 * Author: cg
 * Date: 2024/11/17 19:18
 * Content:
 */
public class ExcelUtils {
//    protected static Logger logger = LoggerFactory.getLogger(ExcelUtils.class);

    /**
     * 读取excel：读取excel数据，封装到实体类中
     *
     * @param file：文件
     * @param entity：实体类
     * @param startRowIndex：开始行数
     * @param startRowIndex：结束行数
     * @return
     */
    public static <T> List<T> readExcelListBean(MultipartFile file, Class<T> entity, Integer headerRowIndex, Integer startRowIndex,String rootPath) {
        String excel = "xls,slxs,xlsx";
        if (headerRowIndex == null) {
            headerRowIndex = 1;
        }
        if (startRowIndex == null) {
            startRowIndex = 2;
        }
        if (file.isEmpty()) {
            R.throwMsg(false, "请上传excel文件");
        }
        String originalFileName = file.getOriginalFilename();
        String extensionName = originalFileName.substring(originalFileName.lastIndexOf(".") + 1, originalFileName.length()).toLowerCase();
        if (!excel.contains(extensionName)) {
            R.throwMsg(false, "excel格式不符合格式要求");
        }
        Long fileId = SnowFlakeUtil.getId();// 批次ID号
        File destFile = null;
        try {
            String fileName = fileId + "." + extensionName;
            // 根据系统判断，如果是windows，则文件路径为：C:/yuanxiao/file/，如果是linux，则文件路径为：/yuanxiao/file/
            String sys_file_dir = "/yuanxiao/file";
            if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                sys_file_dir = "C:/yuanxiao/file";
            }
            if (StringUtils.isNotBlank(rootPath)) {
                sys_file_dir = rootPath;
            }
            String shortPath = StrUtil.format("/excel/import/{}/{}", DateFormatUtils.format(new Date(), "yyyyMM"),fileName);
            String filePath = sys_file_dir + shortPath;
            destFile = new File(filePath);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            // 写入文件
            file.transferTo(destFile);
            ExcelReader reader = ExcelUtil.getReader(filePath);
//            List<Map<String,Object>> readAll = reader.read(3,4,Integer.MAX_VALUE);
            List<T> list = reader.read(headerRowIndex, startRowIndex,Integer.MAX_VALUE, entity);
            // 删除文件
            if (destFile.exists()) {
                destFile.delete();
            }
            if (list.size() <= 0) {
                R.throwMsg(false, "excel数据为空");
            }
            // 将读取的readAll，映射并封装到实体类中
            return list;
        } catch (Exception e) {
//            logger.error(e.getMessage());
            if (destFile.exists()) {
                destFile.delete();
            }
            R.throwMsg(false, "excel操作失败,服务器处理异常");
        }
        return new ArrayList<>();
    }
}
